// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package user

import (
	"audio-server/internal/model"
	"context"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserPageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserPageLogic {
	return &UserPageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserPageLogic) UserPage(req *types.UserPageReq) (resp *types.UserPageRes, err error) {
	pageNum := req.PageNum
	if pageNum <= 0 {
		pageNum = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 10
	}

	offset := (pageNum - 1) * pageSize

	usersModel := model.NewUsersModel(l.svcCtx.Conn)
	userList, err := usersModel.FindUserPage(l.ctx, offset, pageSize)
	if err != nil {
		return nil, err
	}
	var result []types.UserRes
	for _, user := range userList {
		userRes := types.UserRes{
			Id:         user.Id,
			Username:   user.Username,
			Nickname:   user.Nickname,
			Avatar:     user.Avatar,
			Gender:     int(user.Gender),
			RoleIds:    user.RoleIds,
			CreateTime: user.CreateTime.Format("2006-01-02 15:04:05"),
		}
		result = append(result, userRes)
	}
	count, err := usersModel.FindUserCount(l.ctx)

	return &types.UserPageRes{Total: count, List: result}, nil
}
